package easy.netty.net.core.ws;

import easy.netty.net.core.Endpoint;
import easy.netty.net.core.IoHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;

/**
 * @author cengy
 */
public class WsServerIoHandler
        extends IoHandler {

    public WsServerIoHandler(Endpoint endpoint) {
        super(endpoint);
    }

    protected WebSocketServerHandshaker handshaker;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // do nothing
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    protected void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

        if (!request.getDecoderResult().isSuccess()) {

            sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.BAD_REQUEST));
            return;
        }

        if (request.getMethod() != HttpMethod.GET) {
            sendHttpResponse(ctx, request,
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                            HttpResponseStatus.FORBIDDEN));
            return;
        }
        if ("/".equals(request.getUri())) {

            // not support "/"?
            return;
        }

        if ("/favicon.ico".equals(request.getUri())) {

            FullHttpResponse response =
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                            HttpResponseStatus.NOT_FOUND);
            sendHttpResponse(ctx, request, response);
            return;
        }
        // handshake
        WebSocketServerHandshakerFactory wsFactory =
                new WebSocketServerHandshakerFactory(
                        getWebSocketLocation(request), null, true
                );
        this.handshaker = wsFactory.newHandshaker(request);
        if (null == handshaker) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            ChannelFuture future = handshaker.handshake(ctx.channel(), request);

            if (future.isSuccess()) {
                super.channelActive(ctx);
            }
        }
    }

    protected void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
            return;
        }

        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content()));

            return;
        }

        // TextWebSocketFrame
        // BinaryWebSocketFrame
        // ...
        super.channelRead0(ctx, frame);
    }

    protected static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse response) {

        if (response.getStatus().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(response.getStatus().toString(), CharsetUtil.UTF_8);
            response.content().writeBytes(buf);
            buf.release();
            HttpHeaders.setContentLength(response, response.content().readableBytes());
        }

        ChannelFuture f = ctx.channel().writeAndFlush(response);
        if (!HttpHeaders.isKeepAlive(request) ||
                response.getStatus().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }


    private String getWebSocketLocation(FullHttpRequest request) {
        String location = request.headers().get(HttpHeaders.Names.HOST) +
                "/" + endpoint.getIoConf().getWsLocation();

        // @fixme, wss
        return "ws://" + location;
    }
}
